package com.peng.leetcode.other;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * TowSum
 *
 * @author: lupeng6
 * @create: 2020/9/30 15:33
 */
public class TowSum {


    public static void main(String[] args) {
        int[] nums = {3, 3};
        int target = 6;
//        System.out.println(new Solution().twoSum(nums, target));
//        System.out.println(Arrays.toString(new Solution1().twoSum(nums, target)));
        System.out.println(Arrays.toString(new Solution2().twoSum(nums, target)));
    }

}

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ret = new int[2];

        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = 1; j < nums.length; j++) {
                int sum = nums[i] + nums[j];
                if (sum == target) {
                    ret[0] = i;
                    ret[1] = j;
                    return ret;
                }
            }
        }

        return ret;
    }
}


class Solution1 {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }

        for (int i = 0; i < nums.length; i++) {
            int reduce = target - nums[i];
            if (map.containsKey(reduce) && map.get(reduce) != i) {
                return new int[] {i, map.get(reduce)};
            }
        }

        throw new RuntimeException("not find");
    }
}


class Solution2 {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);

            int reduce = target - nums[i];
            if (map.containsKey(reduce) && map.get(reduce) != i) {
                return new int[] {map.get(reduce), i};
            }
        }

        throw new RuntimeException("not find");
    }
}